﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Timers;
using METU_CMT.Business;
using METU_CMT.DataSets.METUCMTDataSetTableAdapters;

namespace METU_CMT
{
    public class Global : System.Web.HttpApplication
    {

        private void CreateTimers()
        {
            Timer _webServiceTimer = new Timer { Enabled = true, Interval = (60000 * 1) };
            _webServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(WebServiceTimer_Elapsed);

            Email _email = new Email("Timer is started", "Timer is started at " + DateTime.Now.ToString("dd.MM.yyyy HH:mm"),
                                     "alprsglm@gmail.com");
            _email.SendEmail();
        }

        private void WebServiceTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            List<Event> _events = EntityFactory.GetAllEvents();
            foreach (Event _event in _events)
            {
                if (_event.DueDate.CompareTo(DateTime.Now) < 0 && _event.MailState == 0 && _event.SubmissionExist == true)
                {
                    EventTableAdapter _eventTableAdapter = new EventTableAdapter();
                    Course _course = _eventTableAdapter.GetCourseOfEvent(_event.EventId);

                    IEnumerable<Team> _teamsNoSubmission =
                        _course.Teams.Where(
                            team => team.Deliverables.Any(deliverable => deliverable.Event.EventId == _event.EventId) == false);
                    string _toList;
                    Email _email;
                    foreach (Team _team in _teamsNoSubmission)
                    {
                        _toList = string.Empty;
                        foreach (Student _student in _team.Members)
                        {
                            _toList += _student.Email + ";";
                        }
                        _email = new Email("Missed Assignment",
                                           "You as " + _team.TeamName + " have missed the submission deadline for the assignment descripted below <br/> Description:" +
                                           _event.Description + "<br/> Due Time:" + _event.DueDate.ToString("dd.MM.yyyy HH:mm"),
                                           _toList);
                        _email.SendEmail();

                        ReviewTeam _reviewTeam =
                            _course.ReviewTeams.FindLast(reviewTeam => reviewTeam.ReviewedTeam.TeamId == _team.TeamId);

                        if (_reviewTeam != null)
                        {
                            _toList = string.Empty;
                            foreach (Student _student in _reviewTeam.ReviewerTeam.Members)
                            {
                                _toList += _student.Email + ";";
                            }
                            _email = new Email("Reviewed Team Missed Assignment",
                                               "The team (" + _team.TeamName +
                                               ") you will review have missed the submission deadline for the assignment descripted below <br/> Description:" +
                                               _event.Description + "<br/> Due Time:" + _event.DueDate.ToString("dd.MM.yyyy HH:mm"),
                                               _toList);
                            _email.SendEmail();
                        }

                        _toList = string.Empty;
                        foreach (TeachingAssistant _teachingAssistant in _course.TAs)
                        {
                            _toList += _teachingAssistant.Email + ";";
                        }
                        _email = new Email("Team Missed Assignment",
                                               "The team (" + _team.TeamName +
                                               ") have missed the submission deadline for the assignment descripted below <br/> Description:" +
                                               _event.Description + "<br/> Due Time:" + _event.DueDate.ToString("dd.MM.yyyy HH:mm"),
                                               _toList);
                        _email.SendEmail();
                    }


                    IEnumerable<Team> _teamsWithSubmission =
                        _course.Teams.Where(
                            team =>
                            team.Deliverables.Any(deliverable => deliverable.Event.EventId == _event.EventId) == true);
                    _toList = string.Empty;
                    foreach (Team _team in _teamsWithSubmission)
                    {
                        foreach (Student _student in _team.Members)
                        {
                            _toList += _student.Email + ";";
                        }
                    }
                    
                    foreach (TeachingAssistant _teachingAssistant in _course.TAs)
                    {
                        _toList += _teachingAssistant.Email + ";";
                    }

                    foreach (Instructor _instructor in _course.Instructors)
                    {
                        _toList += _instructor.Email + ";";
                    }

                    _email = new Email("Deadline has passed" ,
                                       "The submission deadline for the assignment descripted below has passed <br/> Description:" +
                                       _event.Description + "<br/> Due Time:" + _event.DueDate.ToString("dd.MM.yyyy HH:mm"),
                                       _toList);
                    _email.SendEmail();

                    EventsTableAdapter _eventsTableAdapter = new EventsTableAdapter();
                    _eventsTableAdapter.IncrementMailState(_event.EventId);

                }

            }
        }


        void Application_Start(object sender, EventArgs e)
        {
            CreateTimers();
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs
            Exception _objErr = Server.GetLastError().GetBaseException();
            Type _typeException = _objErr.GetType();

            if (_typeException.FullName != null && _typeException.FullName.CompareTo("System.InvalidCastException") == 0)
            {
                Response.Redirect("~/NotAuthorized.htm");
            }
            //if(_typeException.FullName != null && _typeException.FullName.CompareTo("System.NullReferenceException") == 0 )
            //{
            //    Response.Redirect("/NotAuthorized.htm");
            //}
        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

    }
}
